#include <stdlib.h>
#include <stdio.h>
#include <string.h>


#include "structure.h"

void write_buffer(char * buffer, struct global_base *d, int portno){
  sprintf(buffer, "announce listen %d ", portno);
  struct database *tmp;
  char  buf[500], buff_seed[500], buff_leech[500];
  //Rajouter condition si d == NULL
  for (tmp = d->first ; tmp != NULL ; tmp = tmp->next){
    if (tmp->file->type == SEED){
      sprintf(buf, "%s %d %d %s ", tmp->file->name, tmp->file->size, tmp->file->piece_size, tmp->file->key);
      strcat(buff_seed,buf);
    }
    else if (tmp->file->type == LEECH){
      sprintf(buf, "%s ", tmp->file->key);
      strcat(buff_leech,buf);
    }
    else {
      fprintf(stderr,"Incompatible file type.\n");
    }
  }
  strcat(buffer, "seed [ ");
  strcat(buffer, buff_seed);
  strcat(buffer, "]");
  strcat(buffer, " leech [ ");
  strcat(buffer, buff_leech);
  strcat(buffer, "]\n");
}

struct global_base *global_base_create(){
  struct global_base *tmp = malloc(sizeof(struct global_base));
  tmp->first = NULL;
  tmp->length = 0;
  return tmp;
}

void add_file(struct global_base *d, struct file *f){
  if (d->first == NULL){
    d->first =  malloc(sizeof(struct database));
    d->first->file = f;
    d->first->next = NULL;
  }
  else {
    struct database *tmp = d->first;
    while(tmp->next != NULL){
      tmp = tmp->next;
    }
    tmp->next = malloc(sizeof(struct database));
    tmp->next->file = f;
    tmp->next->next = NULL;
  }
}
